//========================================================================
//Copyright 2007-2010 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at 
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================

package com.dyuproject.kvstore.bdb;

import java.io.File;
import java.util.List;

import com.dyuproject.kvstore.Serializer;
import com.google.common.collect.Lists;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Durability;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

/**
 * Configuration for the bdb environment.
 * 
 * @author David Yu
 * @created Jan 28, 2010
 */
public class BDBTestConfig
{
    Environment environment;
    EnvironmentConfig envConfig;
    File tempDir;
    DatabaseConfig databaseConfig;
    List<BDBStore<?>> created = Lists.newArrayList();

    public BDBTestConfig() throws Exception
    {
        envConfig = new EnvironmentConfig();
        envConfig.setDurability(Durability.COMMIT_WRITE_NO_SYNC);
        envConfig.setAllowCreate(true);
        envConfig.setTransactional(true);
        tempDir = new File("target/bdbtest");
        tempDir.mkdir();
        environment = new Environment(this.tempDir,envConfig);
        databaseConfig = new DatabaseConfig();
        databaseConfig.setAllowCreate(true);
        databaseConfig.setTransactional(true);
        databaseConfig.setSortedDuplicates(false);
    }

    public <T> BDBStore<T> newStore(Serializer<T> serializer) throws Exception
    {
        BDBStore<T> p = new BDBStore<T>(serializer, environment, 
                environment.openDatabase(null, "test", databaseConfig));

        created.add(p);
        return p;
    }

    public void destroy() throws Exception
    {
        for (BDBStore<?> p : created)
            p.database.close();
        environment.close();
        for (File f : tempDir.listFiles())
            f.delete();
        tempDir.delete();

    }
}
